﻿using Microsoft.Phone.Shell;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TileDemo
{
    /// <summary>
    /// Possible handle application tile and secornd tile
    /// </summary>
    public class TileHelper
    {
        public ShellTileData tileData { get; set; }
        public bool isWideTile { get; set; }
        public Uri tileUri { get; set; }

        public TileHelper() 
        {
            isWideTile = true;
        }
        /// <summary>
        /// Create second tile
        /// </summary>
        public void Create()
        {
            ShellTile.Create(tileUri, tileData, isWideTile);
        }
        /// <summary>
        /// Update application tile and second tile. case term none or null update application tile
        /// </summary>
        /// <param name="term">id second tile</param>
        public void Update(string term = null) 
        {
            if(term == null){
                ShellTile _Tile = ShellTile.ActiveTiles.FirstOrDefault();

                _Tile.Update(tileData);
            }else{
                Find(term, _true =>
                {
                    _true.Update(tileData);
                },
                _false =>
                {
                }); 
            }           
        }
        /// <summary>
        /// Find for second tile
        /// </summary>
        /// <param name="term">id second tile</param>
        /// <param name="_true">action case true</param>
        /// <param name="_false">action case false</param>
        private void Find(string term, Action<ShellTile> _true, Action<object> _false)
        {
            ShellTile Tile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains(term.ToString()));

            if (Tile != null && Tile.NavigationUri.ToString().Contains(term))
            {
                _true(Tile);
            }
            else 
            {
                _false(null);
            }
        }
        /// <summary>
        /// Find and delete second tile
        /// </summary>
        /// <param name="term">id second tile</param>
        public void FindDelete(string term)
        {
            Find(term, _true => 
            {
                _true.Delete();
            },
            _false => 
            {
            });
        }
    }
}
